package com.spoto.oa.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.oreilly.servlet.MultipartRequest;
import com.spoto.oa.model.Employee;
import com.spoto.oa.model.Product;
import com.spoto.oa.service.ProductServ;
import com.spoto.oa.service.impl.ProductServImpl;
import com.spoto.oa.util.RandomFileRenamePolicy;

public class ProductServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Product product = new Product();
		List<Product> products = null;
		ProductServ proServ = new ProductServImpl();
		String op_type = request.getParameter("op_type");
		HttpSession session=request.getSession();
		Employee loginEmployee=(Employee) session.getAttribute("login_emp");
		List<Product> conflictProducts = new ArrayList<Product>();
		if (op_type.equals("search")) {
			String searchType = request.getParameter("searchType");
			String infor = request.getParameter("infor");
			products = proServ.search(searchType, infor);
			request.setAttribute("products", products);
			request.setAttribute("infor", infor);
			request.setAttribute("searchType", searchType);
			request.getRequestDispatcher("/product/welcome_product.jsp")
					.forward(request, response);
		} else if (op_type.equals("add")) {
			product.setCode(request.getParameter("code"));			
			product.setCompany(request.getParameter("company"));
			product.setCreator(loginEmployee.getUsername());
			product.setDate(new java.sql.Date(new java.util.Date().getTime()));
			product.setFloatPrice(Float.parseFloat(request
					.getParameter("floatPrice")));
			product.setName(request.getParameter("name"));
			product.setPrice(Float.parseFloat(request.getParameter("price")));
			product.setSalesPrice(Float.parseFloat(request
					.getParameter("salesPrice")));
			product.setType(request.getParameter("type"));
			System.out.println(product.getType());
			product.setRemarks(request.getParameter("remarks"));
			try {
				proServ.addProduct(product);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			products = proServ.getAllProducts();
			request.setAttribute("products", products);
			request.getRequestDispatcher("/product/welcome_product.jsp?op_type=search&searchType=code")
					.forward(request, response);
		} else if (op_type.equals("to_update") || op_type.equals("to_list")) {
			String code = request.getParameter("code");
			products = proServ.searchByCode(code);
			request.setAttribute("product", products.get(0));
			if ("to_update".equals(op_type)) {
				request.getRequestDispatcher(
						"/product/update_product.jsp?op_type=update")
						.forward(request, response);
			} else if ("to_list".equals(op_type)) {
				request.getRequestDispatcher(
						"product/update_product.jsp?op_type=list").forward(
						request, response);
			}
		} else if (op_type.equals("update")) {
			int id = Integer.parseInt(request.getParameter("id"));
			product.setCode(request.getParameter("code"));
			product.setCompany(request.getParameter("company"));
			product.setCreator(loginEmployee.getUsername());
			product.setDate(new java.sql.Date(new java.util.Date().getTime()));
			product.setFloatPrice(Float.parseFloat(request
					.getParameter("floatPrice")));
			product.setName(request.getParameter("name"));
			product.setPrice(Float.parseFloat(request.getParameter("price")));
			product.setSalesPrice(Float.parseFloat(request
					.getParameter("salesPrice")));
			product.setType(request.getParameter("type"));
			product.setRemarks(request.getParameter("remarks"));
			proServ.updateProduct(id, product);
			products = proServ.getAllProducts();
			request.setAttribute("products", products);
			request.getRequestDispatcher("/product/welcome_product.jsp")
					.forward(request, response);
		} else if (op_type.equals("delete")) {
			String code = request.getParameter("code");
			proServ.deleteProduct(proServ.selectByCode(code));
			response.setContentType("text/html");
			response.setCharacterEncoding("gbk");
			products = proServ.getAllProducts();
			request.setAttribute("products", products);
			request.getRequestDispatcher("/product/welcome_product.jsp")
					.forward(request, response);
		} else if (op_type.equals("multi_del")) {
			String[] delCodes = request.getParameterValues("del-flag");
			for (int i = 0; i < delCodes.length; i++) {
				Product productDel = proServ.selectByCode(delCodes[i]);
				proServ.deleteProduct(productDel);
			}

			products = proServ.getAllProducts();
			request.setAttribute("products", products);
			request.getRequestDispatcher("/product/welcome_product.jsp")
					.forward(request, response);
		} else if (op_type.equals("upload")) {
			// 存绝对路径
			// String filePath = "C://upload";
			// 存相对路径
			String filePath = "D:\\";
			File uploadPath = new File(filePath);
			// 检查文件夹是否存在 不存在 创建一个
			if (!uploadPath.exists()) {
				uploadPath.mkdir();
			}
			// 文件最大容量 5M
			int fileMaxSize = 5 * 1024 * 1024;
			// 存放文件描述
			String[] fileDiscription = { null, null };
			// 文件名
			String fileName = null;
			// 上传文件数
			int fileCount = 0;
			// 重命名策略
			RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
			// 上传文件
			MultipartRequest mulit = new MultipartRequest(request, filePath,
					fileMaxSize, "utf-8", rfrp);
			filePath += rfrp.getFileName();

			// 将Excel文件读入数据库
			// 封装Employee
			InputStream inp = new FileInputStream(filePath);
			// InputStream inp = new FileInputStream("workbook.xlsx");

			HSSFWorkbook wb = new HSSFWorkbook(inp);// 可以看作是在虚拟下架构出一个workbook
			// 读取文件中的第一张表格
			HSSFSheet sheet = wb.getSheetAt(0);
			// 定义 row、cell
			HSSFRow row;
			// HSSFCell cell;
			String cell;

			// 循环输出表格中的内容
			for (int i = sheet.getFirstRowNum(); i < sheet
					.getPhysicalNumberOfRows(); i++) {
				product = new Product();
				row = sheet.getRow(i);
				int j = row.getFirstCellNum();
				product.setCode(row.getCell(0 + j).toString());
				product.setName(row.getCell(1 + j).toString());
				product.setDate(new java.sql.Date(row.getCell(2 + j)
						.getDateCellValue().getTime()));
				product.setCreator(row.getCell(3 + j).toString());
				product.setType(row.getCell(4 + j).toString());
				product.setPrice((float) row.getCell(5 + j)
						.getNumericCellValue());
				product.setSalesPrice((float) row.getCell(6 + j)
						.getNumericCellValue());
				product.setFloatPrice((float) row.getCell(7 + j)
						.getNumericCellValue());
				product.setCompany(row.getCell(8 + j).toString());
				product.setRemarks(row.getCell(9 + j).toString());
				try {
					proServ.addProduct(product);
				} catch (SQLException e) {
					try {
						conflictProducts.add(product);
						proServ.saveConflict(product);
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
			if (conflictProducts.size() != 0) {
				request.setAttribute("conflictProducts", conflictProducts);
				request.getRequestDispatcher("/product/list_conflict.jsp")
						.forward(request, response);
			} else {
				products = proServ.getAllProducts();
				request.setAttribute("products", products);
				request.getRequestDispatcher("/product/welcome_product.jsp")
						.forward(request, response);
			}
		} else if (op_type.equals("conflict")) {
			String conflict_op = request.getParameter("conflict_op");
			if (conflict_op.equals("multi_del")) {
				String[] editCodes = request.getParameterValues("edit-flag");
				for (int i = 0; i < editCodes.length; i++) {
					Product productDel = proServ
							.getConflictByCode(editCodes[i]);
					proServ.deleteProductConflict(productDel);
				}
			} else if (conflict_op.equals("multi_update")) {
				String[] editCodes = request.getParameterValues("edit-flag");
				for (int i = 0; i < editCodes.length; i++) {
					product = proServ.selectByCode(editCodes[i]);
					Product productUpdate = proServ
							.getConflictByCode(editCodes[i]);
					proServ.updateProduct(product.getId(), productUpdate);
					proServ.deleteProductConflict(productUpdate);
				}
			} else if (conflict_op.equals("delete")) {
				String code = request.getParameter("code");
				Product productDel = proServ.getConflictByCode(code);
				proServ.deleteProductConflict(productDel);
			} else if (conflict_op.equals("update")) {
				String code = request.getParameter("code");
				product = proServ.selectByCode(code);
				Product productUpdate = proServ.getConflictByCode(code);
				proServ.updateProduct(product.getId(), productUpdate);
				proServ.deleteProductConflict(productUpdate);
			}
			conflictProducts = proServ.getAllConflict();
			request.setAttribute("conflictProducts", conflictProducts);
			request.getRequestDispatcher("/product/list_conflict.jsp").forward(
					request, response);
		}
	}

	public ProductServlet() {
		super();
	}

}
